#include "SettingsController.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>
#include <QFileInfo>
#include <QDateTime>
#include <QSysInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDesktopServices>
#include <QUrl>
#include <QDebug>

SettingsController::SettingsController(QObject *parent)
    : QObject(parent),
      m_config(nullptr),
      m_logger(nullptr),
      m_databaseService(nullptr)
{
}

SettingsController::~SettingsController()
{
}

// 设置配置管理器
void SettingsController::setConfig(Config *config)
{
    m_config = config;
    qDebug() << "SettingsController: 设置 Config";
}

// 设置日志管理器
void SettingsController::setLogger(Logger *logger)
{
    m_logger = logger;
    qDebug() << "SettingsController: 设置 Logger";
}

// 设置数据库服务
void SettingsController::setDatabaseService(DatabaseService *dbService)
{
    m_databaseService = dbService;
    qDebug() << "SettingsController: 设置 DatabaseService";
}

// 获取数据库大小
qint64 SettingsController::databaseSize() const
{
    if (!m_databaseService)
        return 0;

    QFileInfo dbFile(m_databaseService->database().databaseName());
    return dbFile.size();
}

// 获取自动清理开关
bool SettingsController::autoCleanupEnabled() const
{
    if (!m_config)
        return true;

    return m_config->autoCleanupEnabled();
}

// 设置自动清理开关
void SettingsController::setAutoCleanupEnabled(bool enabled)
{
    if (!m_config)
        return;

    m_config->setBool("auto_cleanup_enabled", enabled);
    emit autoCleanupEnabledChanged();
    emit configChanged("auto_cleanup_enabled", enabled);

    if (m_logger)
    {
        m_logger->logOperation("set_config", "auto_cleanup_enabled",
                               enabled ? "启用自动清理" : "禁用自动清理");
    }
}

// 获取采集周期
int SettingsController::getPollInterval() const
{
    return m_config ? m_config->pollInterval() : 1000;
}

// 设置采集周期
bool SettingsController::setPollInterval(int intervalMs)
{
    if (!m_config || intervalMs < 100 || intervalMs > 60000)
        return false;

    bool success = m_config->setInt("poll_interval", intervalMs);
    if (success)
    {
        emit configChanged("poll_interval", intervalMs);
        if (m_logger)
        {
            m_logger->logOperation("set_config", "poll_interval",
                                   QString("设置采集周期: %1ms").arg(intervalMs));
        }
    }

    return success;
}

// 获取实时数据保留天数
int SettingsController::getRealtimeDataRetentionDays() const
{
    return m_config ? m_config->realtimeDataRetentionDays() : 7;
}

// 设置实时数据保留天数
bool SettingsController::setRealtimeDataRetentionDays(int days)
{
    if (!m_config || days < 1 || days > 365)
        return false;

    bool success = m_config->setInt("realtime_data_retention_days", days);
    if (success)
    {
        emit configChanged("realtime_data_retention_days", days);
        if (m_logger)
        {
            m_logger->logOperation("set_config", "realtime_data_retention_days",
                                   QString("设置实时数据保留: %1天").arg(days));
        }
    }

    return success;
}

// 获取分钟数据保留天数
int SettingsController::getMinuteDataRetentionDays() const
{
    return m_config ? m_config->minuteDataRetentionDays() : 30;
}

// 设置分钟数据保留天数
bool SettingsController::setMinuteDataRetentionDays(int days)
{
    if (!m_config || days < 1 || days > 365)
        return false;

    bool success = m_config->setInt("minute_data_retention_days", days);
    if (success)
    {
        emit configChanged("minute_data_retention_days", days);
    }

    return success;
}

// 获取小时数据保留天数
int SettingsController::getHourDataRetentionDays() const
{
    return m_config ? m_config->hourDataRetentionDays() : 365;
}

// 设置小时数据保留天数
bool SettingsController::setHourDataRetentionDays(int days)
{
    if (!m_config || days < 1 || days > 3650)
        return false;

    bool success = m_config->setInt("hour_data_retention_days", days);
    if (success)
    {
        emit configChanged("hour_data_retention_days", days);
    }

    return success;
}

// 获取清理时间
QString SettingsController::getCleanupTime() const
{
    return m_config ? m_config->cleanupTime() : "02:00";
}

// 设置清理时间
bool SettingsController::setCleanupTime(const QString &time)
{
    if (!m_config || !validateTimeFormat(time))
        return false;

    bool success = m_config->setString("cleanup_time", time);
    if (success)
    {
        emit configChanged("cleanup_time", time);
    }

    return success;
}

// 获取温度警告阈值
double SettingsController::getTempWarningThreshold() const
{
    return m_config ? m_config->tempWarningThreshold() : 80.0;
}

// 设置温度警告阈值
bool SettingsController::setTempWarningThreshold(double value)
{
    if (!validateThreshold(value, "temperature"))
        return false;

    bool success = m_config->setDouble("temp_warning_threshold", value);
    if (success)
    {
        emit configChanged("temp_warning_threshold", value);
    }

    return success;
}

// 获取温度严重阈值
double SettingsController::getTempCriticalThreshold() const
{
    return m_config ? m_config->tempCriticalThreshold() : 100.0;
}

// 设置温度严重阈值
bool SettingsController::setTempCriticalThreshold(double value)
{
    if (!validateThreshold(value, "temperature"))
        return false;

    bool success = m_config->setDouble("temp_critical_threshold", value);
    if (success)
    {
        emit configChanged("temp_critical_threshold", value);
    }

    return success;
}

// 获取压力警告阈值
double SettingsController::getPressureWarningThreshold() const
{
    return m_config ? m_config->pressureWarningThreshold() : 500.0;
}

// 设置压力警告阈值
bool SettingsController::setPressureWarningThreshold(double value)
{
    if (!validateThreshold(value, "pressure"))
        return false;

    bool success = m_config->setDouble("pressure_warning_threshold", value);
    if (success)
    {
        emit configChanged("pressure_warning_threshold", value);
    }

    return success;
}

// 获取压力严重阈值
double SettingsController::getPressureCriticalThreshold() const
{
    return m_config ? m_config->pressureCriticalThreshold() : 800.0;
}

// 设置压力严重阈值
bool SettingsController::setPressureCriticalThreshold(double value)
{
    if (!validateThreshold(value, "pressure"))
        return false;

    bool success = m_config->setDouble("pressure_critical_threshold", value);
    if (success)
    {
        emit configChanged("pressure_critical_threshold", value);
    }

    return success;
}

// 获取流量警告阈值
double SettingsController::getFlowWarningThreshold() const
{
    return m_config ? m_config->flowWarningThreshold() : 100.0;
}

// 设置流量警告阈值
bool SettingsController::setFlowWarningThreshold(double value)
{
    if (!validateThreshold(value, "flow"))
        return false;

    bool success = m_config->setDouble("flow_warning_threshold", value);
    if (success)
    {
        emit configChanged("flow_warning_threshold", value);
    }

    return success;
}

// 优化数据库
bool SettingsController::optimizeDatabase()
{
    qInfo() << "SettingsController: 优化数据库";

    if (!m_databaseService)
        return false;

    QSqlDatabase db = m_databaseService->database();
    QSqlQuery query(db);

    // 执行 VACUUM
    if (!query.exec("VACUUM"))
    {
        qWarning() << "SettingsController: VACUUM 失败:" << query.lastError().text();
        emit errorOccurred("数据库优化失败");
        return false;
    }

    // 执行 ANALYZE
    if (!query.exec("ANALYZE"))
    {
        qWarning() << "SettingsController: ANALYZE 失败:" << query.lastError().text();
    }

    emit databaseOptimized();
    if (m_logger)
    {
        m_logger->logOperation("optimize_db", "database", "数据库优化完成");
    }

    refreshDatabaseSize();
    qInfo() << "SettingsController: 数据库优化完成";
    return true;
}

// VACUUM 数据库
bool SettingsController::vacuumDatabase()
{
    if (!m_databaseService)
        return false;

    QSqlQuery query(m_databaseService->database());
    return query.exec("VACUUM");
}

// ANALYZE 数据库
bool SettingsController::analyzeDatabase()
{
    if (!m_databaseService)
        return false;

    QSqlQuery query(m_databaseService->database());
    return query.exec("ANALYZE");
}

// 备份数据库
bool SettingsController::backupDatabase(const QString &backupPath)
{
    qInfo() << "SettingsController: 备份数据库到" << backupPath;

    if (!m_databaseService)
        return false;

    QString dbPath = m_databaseService->database().databaseName();
    QFile dbFile(dbPath);

    if (!dbFile.exists())
    {
        emit errorOccurred("数据库文件不存在");
        return false;
    }

    // 复制数据库文件
    if (!QFile::copy(dbPath, backupPath))
    {
        emit errorOccurred("备份失败");
        return false;
    }

    emit databaseBackupCompleted(backupPath);
    if (m_logger)
    {
        m_logger->logOperation("backup_db", "database",
                               QString("数据库备份到: %1").arg(backupPath));
    }

    qInfo() << "SettingsController: 数据库备份完成";
    return true;
}

// 恢复数据库
bool SettingsController::restoreDatabase(const QString &backupPath)
{
    qInfo() << "SettingsController: 从备份恢复数据库 -" << backupPath;

    if (!m_databaseService)
        return false;

    QFile backupFile(backupPath);
    if (!backupFile.exists())
    {
        emit errorOccurred("备份文件不存在");
        return false;
    }

    QString dbPath = m_databaseService->database().databaseName();

    // 关闭数据库连接
    m_databaseService->closeDatabase();

    // 删除旧数据库
    QFile::remove(dbPath);

    // 复制备份文件
    if (!QFile::copy(backupPath, dbPath))
    {
        emit errorOccurred("恢复失败");
        return false;
    }

    // 重新初始化数据库
    m_databaseService->initialize(dbPath);

    emit databaseRestored();
    if (m_logger)
    {
        m_logger->logOperation("restore_db", "database", "数据库恢复完成");
    }

    refreshDatabaseSize();
    qInfo() << "SettingsController: 数据库恢复完成";
    return true;
}

// 清理旧实时数据
bool SettingsController::clearOldRealtimeData()
{
    int days = getRealtimeDataRetentionDays();
    return cleanOldData("realtime_data", days);
}

// 清理旧分钟数据
bool SettingsController::clearOldMinuteData()
{
    int days = getMinuteDataRetentionDays();
    return cleanOldData("minute_statistics", days);
}

// 清理旧小时数据
bool SettingsController::clearOldHourData()
{
    int days = getHourDataRetentionDays();
    return cleanOldData("hour_statistics", days);
}

// 清空所有历史数据
bool SettingsController::clearAllHistoryData()
{
    qInfo() << "SettingsController: 清空所有历史数据";

    if (!m_databaseService)
        return false;

    QSqlDatabase db = m_databaseService->database();
    QSqlQuery query(db);

    int totalRemoved = 0;

    // 清空实时数据
    if (query.exec("DELETE FROM realtime_data"))
    {
        totalRemoved += query.numRowsAffected();
    }

    // 清空分钟统计
    if (query.exec("DELETE FROM minute_statistics"))
    {
        totalRemoved += query.numRowsAffected();
    }

    // 清空小时统计
    if (query.exec("DELETE FROM hour_statistics"))
    {
        totalRemoved += query.numRowsAffected();
    }

    emit dataCleaned(totalRemoved);
    if (m_logger)
    {
        m_logger->logOperation("clear_all_data", "database",
                               QString("清空所有历史数据，共 %1 条").arg(totalRemoved));
    }

    refreshDatabaseSize();
    qInfo() << "SettingsController: 已清空" << totalRemoved << "条记录";
    return true;
}

// 获取实时数据数量
int SettingsController::getRealtimeDataCount() const
{
    return getTableRecordCount("realtime_data");
}

// 获取分钟数据数量
int SettingsController::getMinuteDataCount() const
{
    return getTableRecordCount("minute_statistics");
}

// 获取小时数据数量
int SettingsController::getHourDataCount() const
{
    return getTableRecordCount("hour_statistics");
}

// 获取报警数量
int SettingsController::getAlarmCount() const
{
    return getTableRecordCount("alarm_records");
}

// 获取设备数量
int SettingsController::getDeviceCount() const
{
    return getTableRecordCount("devices");
}

// 获取数据库路径
QString SettingsController::getDatabasePath() const
{
    if (!m_databaseService)
        return QString();

    return m_databaseService->database().databaseName();
}

// 清理操作日志
bool SettingsController::clearOperationLogs(int daysToKeep)
{
    qInfo() << "SettingsController: 清理操作日志，保留" << daysToKeep << "天";

    if (!m_databaseService)
        return false;

    QDateTime cutoffTime = QDateTime::currentDateTime().addDays(-daysToKeep);
    QSqlQuery query(m_databaseService->database());

    query.prepare("DELETE FROM operation_logs WHERE timestamp < ?");
    query.addBindValue(cutoffTime.toString("yyyy-MM-dd HH:mm:ss"));

    if (!query.exec())
    {
        qWarning() << "SettingsController: 清理日志失败:" << query.lastError().text();
        return false;
    }

    int removedCount = query.numRowsAffected();
    emit dataCleaned(removedCount);

    qInfo() << "SettingsController: 清理完成，删除" << removedCount << "条日志";
    return true;
}

// 获取操作日志数量
int SettingsController::getOperationLogCount() const
{
    return getTableRecordCount("operation_logs");
}

// 获取日志文件路径
QString SettingsController::getLogFilePath() const
{
    if (!m_logger)
        return QString();

    // 假设日志文件在 logs/application.log
    return "logs/application.log";
}

// 打开日志文件
bool SettingsController::openLogFile()
{
    QString logPath = getLogFilePath();
    if (logPath.isEmpty() || !QFile::exists(logPath))
        return false;

    return QDesktopServices::openUrl(QUrl::fromLocalFile(logPath));
}

// 获取系统信息
QString SettingsController::getSystemInfo() const
{
    QString info;
    info += QString("操作系统: %1\n").arg(QSysInfo::prettyProductName());
    info += QString("内核版本: %1\n").arg(QSysInfo::kernelVersion());
    info += QString("CPU 架构: %1\n").arg(QSysInfo::currentCpuArchitecture());
    info += QString("Qt 版本: %1\n").arg(qVersion());
    info += QString("应用版本: %1\n").arg(appVersion());
    return info;
}

// 获取 Qt 版本
QString SettingsController::getQtVersion() const
{
    return qVersion();
}

// 获取构建日期
QString SettingsController::getBuildDate() const
{
    return QString("%1 %2").arg(__DATE__).arg(__TIME__);
}

// 导出配置
bool SettingsController::exportConfig(const QString &filePath)
{
    qInfo() << "SettingsController: 导出配置到" << filePath;

    if (!m_config)
        return false;

    QMap<QString, QString> allConfig = m_config->getAllConfig();
    QJsonObject jsonObj;

    for (auto it = allConfig.constBegin(); it != allConfig.constEnd(); ++it)
    {
        jsonObj[it.key()] = it.value();
    }

    QJsonDocument doc(jsonObj);
    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly))
    {
        emit errorOccurred("无法创建配置文件");
        return false;
    }

    file.write(doc.toJson());
    file.close();

    if (m_logger)
    {
        m_logger->logOperation("export_config", "config", QString("导出配置到: %1").arg(filePath));
    }

    qInfo() << "SettingsController: 配置导出完成";
    return true;
}

// 导入配置
bool SettingsController::importConfig(const QString &filePath)
{
    qInfo() << "SettingsController: 从" << filePath << "导入配置";

    if (!m_config)
        return false;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly))
    {
        emit errorOccurred("无法读取配置文件");
        return false;
    }

    QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    file.close();

    if (!doc.isObject())
    {
        emit errorOccurred("配置文件格式错误");
        return false;
    }

    QJsonObject jsonObj = doc.object();
    for (auto it = jsonObj.constBegin(); it != jsonObj.constEnd(); ++it)
    {
        m_config->setString(it.key(), it.value().toString());
    }

    if (m_logger)
    {
        m_logger->logOperation("import_config", "config", "导入配置");
    }

    qInfo() << "SettingsController: 配置导入完成";
    return true;
}

// 重置为默认配置
bool SettingsController::resetToDefaultConfig()
{
    qInfo() << "SettingsController: 重置为默认配置";

    if (!m_config)
        return false;

    // 设置默认值
    m_config->setInt("poll_interval", 1000);
    m_config->setDouble("temp_warning_threshold", 80.0);
    m_config->setDouble("temp_critical_threshold", 100.0);
    m_config->setDouble("pressure_warning_threshold", 500.0);
    m_config->setDouble("pressure_critical_threshold", 800.0);
    m_config->setDouble("flow_warning_threshold", 100.0);
    m_config->setInt("realtime_data_retention_days", 7);
    m_config->setInt("minute_data_retention_days", 30);
    m_config->setInt("hour_data_retention_days", 365);
    m_config->setBool("auto_cleanup_enabled", true);
    m_config->setString("cleanup_time", "02:00");

    if (m_logger)
    {
        m_logger->logOperation("reset_config", "config", "重置为默认配置");
    }

    qInfo() << "SettingsController: 配置重置完成";
    return true;
}

// 刷新数据库大小
void SettingsController::refreshDatabaseSize()
{
    emit databaseSizeChanged();
}

// 验证阈值有效性
bool SettingsController::validateThreshold(double value, const QString &name)
{
    if (value < 0 || value > 10000)
    {
        qWarning() << "SettingsController: 无效的阈值:" << name << value;
        return false;
    }
    return true;
}

// 验证时间格式
bool SettingsController::validateTimeFormat(const QString &time)
{
    QRegExp rx("^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$");
    return rx.exactMatch(time);
}

// 获取表记录数
int SettingsController::getTableRecordCount(const QString &tableName) const
{
    if (!m_databaseService)
        return 0;

    QSqlQuery query(m_databaseService->database());
    QString sql = QString("SELECT COUNT(*) FROM %1").arg(tableName);

    if (query.exec(sql) && query.next())
    {
        return query.value(0).toInt();
    }

    return 0;
}

// 清理旧数据
bool SettingsController::cleanOldData(const QString &tableName, int daysToKeep)
{
    qInfo() << "SettingsController: 清理旧数据 -" << tableName << "保留" << daysToKeep << "天";

    if (!m_databaseService)
        return false;

    QDateTime cutoffTime = QDateTime::currentDateTime().addDays(-daysToKeep);
    QSqlQuery query(m_databaseService->database());

    QString sql = QString("DELETE FROM %1 WHERE timestamp < ?").arg(tableName);
    query.prepare(sql);
    query.addBindValue(cutoffTime.toString("yyyy-MM-dd HH:mm:ss"));

    if (!query.exec())
    {
        qWarning() << "SettingsController: 清理失败:" << query.lastError().text();
        emit errorOccurred("数据清理失败");
        return false;
    }

    int removedCount = query.numRowsAffected();
    emit dataCleaned(removedCount);

    if (m_logger)
    {
        m_logger->logOperation("clean_data", tableName,
                               QString("清理旧数据，删除 %1 条记录").arg(removedCount));
    }

    refreshDatabaseSize();
    qInfo() << "SettingsController: 清理完成，删除" << removedCount << "条记录";
    return true;
}
